package com.em.controller;

import com.em.common.model.SysUser;
import com.em.frame.shiro.ShiroCache;
import com.em.frame.utils.ResponseUtil;
import com.em.frame.utils.StringUtil;
import com.jfinal.core.Controller;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;


/**
 * Created by zlx on 2017/11/22 0022.
 */
public class IndexController extends Controller {

    private final Logger logger = Logger.getLogger(IndexController.class);

    /**
     * 跳转登陆页面
     * shiro.ini  = /login** = anon
     */
    public void login(){
        render("login.html");
    }

    /**
     * 登陆页认证接口
     * shiro.ini  = /login** = anon
     */
    public void loginAuthc(){
        try {
            String username = getPara("username");
            String password = getPara("password");
            if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
                renderJson(ResponseUtil.ERROR("用户名密码为空"));
                return;
            }
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            try {
                subject.login(token);
                redirect("index");
            }catch (LockedAccountException lockE){
                token.clear();
                renderJson(ResponseUtil.ERROR("用户已锁不能登录，请与管理员联系！"));
            }catch (AuthenticationException authE){
                token.clear();
                renderJson(ResponseUtil.ERROR("用户名或密码错误！"));
            }
        }catch (Exception e){
            logger.error("登陆页认证接口",e);
            renderJson(ResponseUtil.ERROR("出现未知错误，请重新加载"));
        }
    }

    /**
     * 登出
     * shiro.ini  = /logout = anon
     */
    public void logout(){
        try {
            SysUser user =  ShiroCache.getLoginUser();
            if(user == null){
                redirect("login");
                return;
            }
            ShiroCache.userLogout();
            render("login.html");
            System.out.println("### 用户登出 ###");
        }catch (Exception e){
            logger.error("登陆页认证接口",e);
            renderJson(ResponseUtil.ERROR("出现未知错误，请重新加载"));
        }
    }

    /**
     * 项目首页
     * 项目启动时第一次访问，权限无法过滤？ 之后都可以过滤
     */
    public void index(){
        try{
            SysUser user =  ShiroCache.getLoginUser();
            if(user == null){
                redirect("login");
                return;
            }
            renderJson(ResponseUtil.SUCCESS(ShiroCache.getUserAll()));
        }catch (Exception e){
            logger.error("项目首页",e);
            renderJson(ResponseUtil.ERROR("出现未知错误，请重新加载"));
        }
    }


}
